<script setup lang="ts">
import type { DropdownInstance } from 'element-plus'

const props = defineProps({
  items: {
    type: Array as PropType<MyContextMenuItem[]>,
    default: () => [],
  },
  extention: {
    type: Object,
    default: () => ({}),
  },
})
const emit = defineEmits(['visibleChange'])
function onVisibleChange(visible: boolean) {
  emit('visibleChange', visible, props.extention)
}

const dropdownRef = ref<DropdownInstance>()

defineExpose({
  dropdownRef,
  extention: props.extention,
})

function handleCommand(command: MyContextMenuItem) {
  if (command.command) {
    command.command(props.extention)
  }
}
</script>

<template>
  <div class="my-context-menu">
    <el-dropdown ref="dropdownRef" placement="bottom-start" trigger="contextmenu" @command="handleCommand" @visible-change="onVisibleChange">
      <slot />
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
            v-for="(item, idx) in items" :key="idx"
            :command="item" :disabled="item.disabled" :divided="item.divided"
          >
            <i :class="item.icon" />
            <div>{{ item.name }}</div>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>
